<?php

namespace app\admin\controller\census;

use app\common\controller\Backend;
use think\Session;
/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Transaction extends Backend
{

    /**
     * Transaction模型对象
     * @var \app\admin\model\census\Transaction
     */
    protected $model = null;
    protected $order_model = null;
    protected $goods_order_model = null;
    protected $order_item_model = null;
    protected $count_order_model = null;
    protected $shop_id = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->shop_id = Session::get('shop');
        $this->model = new \app\admin\model\census\Transaction;
        $this->order_model = new \app\admin\model\order\Order;
        $this->goods_order_model = new \app\admin\model\order\Goods;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->count_order_model = new \app\admin\model\census\Adate;
        
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->assignconfig('shop_id', $this->shop_id);
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $conditions = '1=1';
            if ($this->shop_id != 1) {
                $conditions = ['transaction.id' => $this->shop_id];
            }
            $list = $this->model
                    ->with(['order'])
                    ->where($where)
                    ->where($conditions)
                    ->order($sort, $order)
                    ->paginate($limit);

            if ($list->total() > 0) {
                $list_data = $list->items();
                foreach ($list_data as $key => &$value) {
                    $conditions = [];
                    $conditions['o.data_type'] = ['in',['cards','goods']];
                    $conditions['o.shop_id'] = $value['id'];
                    $conditions['go.gdtype'] = "0";//0为商品，1为服务
                    $conditions['o.state'] = ['in',['2','3','4','5','6']];//订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
                    $conditions['o.status'] = 'normal';
                    $conditions['o.createtime'] = [['>=',$value['order']['adatetime']],['<=',$value['order']['adatetime'] + 3600 * 24 - 1]];

                    //商品订单金额
                    $value['commodity_order_amount'] = $this->goods_order_model->alias('go')
                                                ->join('wanlshop_order o','o.id = go.order_id','left')
                                                ->where($conditions)
                                                ->sum('go.actual_payment');
                    //商品订单数
                    $value['commodity_order_count'] = $this->goods_order_model->alias('go')
                                                ->join('wanlshop_order o','o.id = go.order_id','left')
                                                ->where($conditions)
                                                ->count('go.order_id');

                    //服务订单金额
                    $conditions['go.gdtype'] = "1";//0为商品，1为服务
                    $value['service_order_amount'] = $this->goods_order_model->alias('go')
                                                ->join('wanlshop_order o','o.id = go.order_id','left')
                                                ->where($conditions)
                                                ->sum('go.actual_payment');
                    //服务订单数
                    $value['service_order_count'] = $this->goods_order_model->alias('go')
                                                ->join('wanlshop_order o','o.id = go.order_id','left')
                                                ->where($conditions)
                                                ->count('go.order_id');

                    //卡项订单金额
                    unset($conditions['go.gdtype']);
                    $value['carditem_order_amount'] = $this->order_item_model->alias('go')
                                                    ->join('wanlshop_order o','o.id = go.order_id','left')
                                                    ->where($conditions)
                                                    ->sum('go.actual_price');

                    //卡项订单数
                    $value['card_order_count'] = $this->order_item_model->alias('go')
                                                    ->join('wanlshop_order o','o.id = go.order_id','left')
                                                    ->where($conditions)
                                                    ->count('go.order_id');

                    //订单总额
                    $value['total_order_fee'] = number_format($value['commodity_order_amount'] + $value['service_order_amount'] + $value['carditem_order_amount'],2);

                    //订单总数
                    $value['total_order_count'] = number_format($value['commodity_order_count'] + $value['service_order_count'] + $value['card_order_count'],0);

                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $params = $this->request->get();
        $shop_id = $params['shop_id'];
        $createtime = $params['createtime'];

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            if (isset($params['filter']) && !empty($params['filter'])) {
                $filter = json_decode($params['filter'],true);
                if (isset($filter['order_no'])) {
                    $filter['o.order_no'] = $filter['order_no'];
                    unset($filter['order_no']);
                }

                if (isset($filter['product_name'])) {
                    $filter['og.title|oi.name'] = $filter['product_name'];
                    unset($filter['product_name']);
                }

                if (isset($filter['goods_type'])) {
                    $filter['og.gdtype'] = $filter['goods_type'];
                    unset($filter['goods_type']);
                }
            }
            $shop_id = $params['shop_id'];
            $createtime = $params['createtime'];
            $conditions = [];
            $conditions['o.shop_id'] = $shop_id;
            $conditions['o.state'] = ['in',['2','3','4','5','6']];//订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
            $conditions['o.status'] = 'normal';
            $conditions['o.createtime'] = [['>=',$createtime],['<=',$createtime + 3600 * 24 - 1]];

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if (isset($params['filter']) && !empty($params['filter'])) {
                $filter = json_decode($params['filter'],true);
                if (isset($filter['order_no'])) {
                    $conditions['o.order_no'] =['like','%'.$filter['order_no'].'%'];

                }

                if (isset($filter['product_name'])) {
                    $conditions['og.title|oi.name'] =['like','%'.$filter['product_name'].'%'];
                }

                if (isset($filter['goods_type'])) {
                    $conditions['og.gdtype'] = $filter['goods_type'];
                }
            }

            $list = $this->order_model->alias('o')
                    ->field("IFNULL(og.id,oi.id) as id, o.order_no as order_no,IFNULL(og.title,oi.name) AS product_name,o.paymenttime as paymenttime,IFNULL(og.gdtype,'2') as goods_type,po.pay_way_id,p.name,o.actual_price as amount")
                    ->where($conditions)
                    ->join('wanlshop_order_goods og','og.order_id = o.id','left')
                    ->join('wanlshop_order_item oi','oi.order_id = o.id','left')
                    ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                    ->join('pay p','po.pay_way_id = p.id','left')
                    ->paginate($limit);

            $total = $list->total();
            $rows = $list->items();

            if ($total > 0) {
                foreach ($rows as $key => &$value) {
                    $value['j_url'] = url('/order/goods/detail/ids/'.$value["id"]);
                    if ($value['goods_type'] == '1') {
                        $value['j_url'] = url('/order/treatment/detail/ids/'.$value["id"]);
                    }elseif ($value['goods_type'] == '2') {
                        $value['j_url'] = url('/order/item/detail/ids/'.$value["id"]);
                    }
                }
            }
            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        
        $this->assignconfig('shop_id', $shop_id);
        $this->assignconfig('createtime', $createtime);
        return $this->view->fetch();
    }

}
